﻿using Md.Api.Entity.DapperModels.MdDB;
using Md.Api.Model.Manage.SysDept.Request;
using Md.Dapper.Repositories.Md;

namespace Md.Api.Service.Manage.SysDept;
/// <summary>
/// 获取系统部门树列表服务
/// </summary>
public class GetSysDeptTreeListService : ApiBase<RequestGetSysDeptListModel>
{
    /// <summary>
    /// 系统部门仓储
    /// </summary>
    public SysDeptRep sysDeptRep { get; set; }
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        var model = new SysDeptModel();

        model.ParentId = Parameter.ParentId.HasValue ? Convert.ToInt64(Parameter.ParentId) : -1;
        model.Ancestors = Parameter.Ancestors;
        model.DeptName = Parameter.DeptName;
        model.Leader = Parameter.Leader;
        model.Phone = Parameter.Phone;
        model.Email = Parameter.Email;
        model.Status = Parameter.Status;
        model.CreateBy = Parameter.CreateBy;
        model.UpdateBy = Parameter.UpdateBy;

        var depts = sysDeptRep.GetSysDeptList(model, Parameter.OrderBy, Parameter.IsDesc).ToList();

        var res = BuildDeptTree(depts, 0);

        Result.Data = res;
    }

    public List<SysDeptModel> BuildDeptTree(List<SysDeptModel> depts, long parentId)
    {
        var result = new List<SysDeptModel>();

        var list = depts.Where(s => s.ParentId == parentId).ToList();

        foreach (var dept in list)
        {
            result.Add(dept);

            var children = BuildDeptTree(depts, dept.DeptId);

            if (children.Count() > 0)
            {
                dept.Children = children;
            }
        }

        return result;
    }
}

